<?php
/**
 * 用户头衔模型类
 */

class UserTitleModel extends Model
{
    private $user_title_id;
    
    /**
     * 构造函数
     * @author 姜伟
     * @todo 构造函数
     */
    public function __construct($user_title_id=0)
    {
        parent::__construct();
        $this->user_title_id = $user_title_id;
    }

    public function getUserTitleNum($where='') {
      return $this->where($where)->count();
    }

    /**
     * 添加头衔
     * @author 姜伟
     * @param array $arr_class 头衔数组
     * @return boolean 操作结果
     * @todo 添加头衔
     */
    public function addUserTitle($arr_class)
    {
        if (!is_array($arr_class)) return false;
        return $this->add($arr_class);
    }

    /**
     * 删除头衔
     * @author 姜伟
     * @param string $user_title_id 头衔ID
     * @return boolean 操作结果
     * @todo 删除头衔
     */
    public function delUserTitle()
    {
        if (!is_numeric($this->user_title_id)) return false;
        return $this->where('user_title_id = ' . $this->user_title_id)->delete();
    }

    public function delUserTitleByTitleId($title_id)
    {
        if (!is_numeric($title_id)) return false;
        return $this->where('title_id = ' . $title_id)->delete();
    }


    /**
     * 更改用户头衔
     * @author 姜伟
     * @param int $user_id 用户ID
     * @param array $new_titles 头衔数组
     * @return boolean 操作结果
     * @todo 更改头衔
     */
    public function setUserTitle($user_id, $new_titles)
    {
        if (!is_numeric($user_id)) return false;
        //计算得出他已有的特殊头衔 和 鉴定师头衔．
        $now_titles = $this->getUserNotOrdinaryTitle($user_id);//已有的头衔
        $old_titles   = array();
        foreach ($now_titles as $k => $v){
            if (!in_array($v['title_id'], $new_titles))
            {
                $this->user_title_id = $v['user_title_id'];
                $r = $this->delUserTitle();
                if($r){
                    $title_name = '';
                    $title_name = M('Title')->where('title_id ='.$v['title_id'])->getField('title_name');
                    D('Message')->addMessage($v['title_id'], 5, 0, $user_id, '您的头衔-'.$title_name.'已被撤销', '您的头衔-'.$title_name.'已被撤销');
                }
            } else {
                $old_titles[] = $v['title_id'];
            }
        }

        foreach ($new_titles as $k0 => $v0){
            $data = array(
                'user_id'=>$user_id,
                'title_id'=>$v0,
                'addtime' =>time(),
            );
            if (in_array($v0, $old_titles))
            {
                continue;
            } else //否则新增一条sku记录
            {
                $r = $this->addUserTitle($data); //执行添加
                if($r){
                    $title_name = '';
                    $title_name = M('Title')->where('title_id ='.$v0)->getField('title_name');
                    D('Message')->addMessage($v0, 5, 0, $user_id, '恭喜，您已获得头衔-'.$title_name, '恭喜，您已获得头衔-'.$title_name);
                }
            }
        }

        return $r;

    }

    /**
     * 获取用户的支付接口权限
     * @param $user_id 用户ID
     * @return bool
     */
    public function getUserPostCash($user_id){
        if (!is_numeric($user_id)) return false;

        $user_post_cash = $this->getUserAlltitle($user_id);

        $user_post_cash = $user_post_cash[0][title_post_cash];

        $user_post_cash = intval($user_post_cash);
        return $user_post_cash;

    }
    /**
     * 更改头衔
     * @author 姜伟
     * @param int $user_title_id 头衔ID
     * @param array $arr_class 头衔数组
     * @return boolean 操作结果
     * @todo 更改头衔
     */
    public function editUserTitle($user_title_id, $arr_class)
    {
        if (!is_numeric($user_title_id) || !is_array($arr_class)) return false;
        return $this->where('user_title_id = ' . $user_title_id)->save($arr_class);
    }

    /**
     * 获取头衔
     * @author 姜伟
     * @param string $where 头衔ID
     * @param string $fields 查询的字段名，默认为空，取全部
     * @return array 头衔
     * @todo 获取头衔
     */
    public function getUserTitle($where, $fields = null)
    {
        return $this->field($fields)->where($where)->find();
    }

    /**
     *根据用户ID获得用户头衔中分成最低的头衔
     * @param $user_id 用户ID
     */
    public function getTitlePostCash($user_id){
        return $this->alias('u')
            ->join('tp_title AS t ON u.title_id = t.title_id')
            ->field('t.title_rates')
            ->where('t.isuse = 1 and u.user_id = ' . $user_id)
            ->order('t.title_rates ASC')
            ->limit(1)
            ->select();
    }

    /**
     * 获取头衔某个字段的信息
     * @author 姜伟
     * @param int $user_title_id 头衔ID
     * @param string $field 查询的字段名
     * @return array 头衔
     * @todo 获取头衔某个字段的信息
     */
    public function getUserTitleField($user_title_id, $field)
    {
        if (!is_numeric($user_title_id))   return false;
        return $this->where('user_title_id = ' . $user_title_id)->getField($field);
    }

    /**
     * 查询该用户是否佩戴该头衔．
     */
    public function getUserTitleIsWear($user_id,$title_id)
    {
        return $this->where('user_id ='.$user_id.' AND title_id='.$title_id)->getField('is_adorn');
    }

    /**
     *  修改用户佩戴头衔
     */
    public function setUserTitleIsWear($user_id,$title_id,$arr)
    {
        return $this->where('user_id ='.$user_id.' AND title_id='.$title_id)->save($arr);
    }

    /**
     * 获取头衔某个字段的信息
     * @author 姜伟
     * @param string $where 条件
     * @param string $field 查询的字段名
     * @return array 头衔
     * @todo 获取头衔某个字段的信息
     */
    public function getUserTitleFields($where, $field)
    {
        return $this->where($where)->getField($field ,true);
    }

    /**
     * 获取所有头衔列表
     * @author 姜伟
     * @param string $where where子句
     * @return array 头衔列表
     * @todo 获取所有头衔列表
     */
    public function getUserTitleList($where = null,$order = null)
    {
        return $this->where($where)->order($order)->select();
    }
 
    /**
     * 获取分类信息
     * @author 姜伟
     * @param string $where where子句
     * @param string $fields 要获取的字段名
     * @return array 商品基本信息
     * @todo 根据where查询条件查找商品表中的相关数据并返回
     */
    public function getUserTitleInfo($where, $fields = '')
    {
		return $this->field($fields)->where($where)->find();
    }

    /**
     * 获取已有的特殊头衔和鉴定师头衔
     */
    public function getUserNotOrdinaryTitle($user_id)
    {
        return $this->alias('u')
            ->join('tp_title AS t ON u.title_id = t.title_id')
            ->field('u.title_id,u.user_id,u.user_title_id')
            ->where('u.user_id = ' . $user_id.' AND (t.type='.TitleModel::SPECIAL.' or t.type='.TitleModel::APPRAISER.')')
            ->limit(1000000)
            ->select();
    }

    /**
     * 判断用户的头衔是否拥有支付接口的权限
     * @param $user_id 用户ID
     * @return mixed 返回用户的支付接口权限
     */
    public function getUserAlltitle($user_id)
    {
        return $this->alias('u')
            ->join('tp_title AS t ON u.title_id = t.title_id')
            ->field('t.title_post_cash')
            ->where('t.isuse = 1 and u.user_id = ' . $user_id)
            ->order('t.title_post_cash desc')
            ->limit(1)
            ->select();


    }

    /**
     * 获取所有头衔并判断用户是否拥有该头衔
     * @param $user_id
     */
    public function getUserTitleLiss($user_id){


        $title_obj = new TitleModel();
        $title_list = $title_obj->getTotalTypeTitleList(TitleModel::SPECIAL);

        //我所有的头衔
        $my_titles = $this->field('title_id')->where('user_id = '.$user_id)->select();
        foreach ($title_list as $k => $val){
            foreach ($my_titles as $v){
                if($val['title_id'] == $v['title_id']){
                    $title_list[$k]['is_receive'] = 1;
                }
            }
        }

        return $title_list;
    }


    /**
     * 判断用户是否有普通头衔．
     */
    public function getUserOrdinaryTitle($user_id){

        //所有的普通头衔．
        $title_obj = new TitleModel();
        $reply_title_list = $title_obj->getOrdinaryTitleFields(TitleModel::REPLY,'title_id');//回帖
        $admire_title_list = $title_obj->getOrdinaryTitleFields(TitleModel::ADMIRE,'title_id');//赞赏
        $share_title_list = $title_obj->getOrdinaryTitleFields(TitleModel::SHARE,'title_id');//分享
        $where = 'type ='.TitleModel::ORDINARY.' AND isuse = 1 ';

        //我已经有的所有头衔．
        $my_titles = $this->getUserTitleFields('user_id ='.$user_id,'title_id');

        //获取用户信息．
        $user_obj = new UserModel();
        $user_info = $user_obj->getUserInfo('','user_id ='.$user_id);

        //回帖的头衔．
        $reply_id = array_intersect($reply_title_list,$my_titles);//我的头衔和所有回帖头衔的值对比
        if(count($reply_id)){//如果有,找出当前头衔升级所需次数．找出更高级头衔
            $title_info =  $title_obj->getTitleInfo('title_id ='.implode(',',$reply_id));
            $reply_info =  $title_obj->getTitleInfo($where.' AND tag_id ='.TitleModel::REPLY.' and rank_up_num >'.$title_info['rank_up_num']);
            if(!$reply_info){//如果没有更高级头衔说明已经领取最高级头衔．
                $reply_info = $title_info;
                $reply_info['is_receive'] = 1;
            }
        }else{
            $reply_info =  $title_obj->getTitleInfo($where.' AND tag_id ='.TitleModel::REPLY);
        }
        //是否满足领取资格．
        $reply_info['is_qualified'] = $user_info['reply_num'] >= $reply_info['rank_up_num'] ? true : false;
        $reply_info['condition_num'] = $user_info['reply_num'];
        //赞赏的头衔．
        $admire_id = array_intersect($admire_title_list,$my_titles);
        if(count($admire_id)){
            $title_info =  $title_obj->getTitleInfo('title_id ='.implode(',',$admire_id));
            $admire_info =  $title_obj->getTitleInfo($where.' AND tag_id ='.TitleModel::ADMIRE.' and rank_up_num >'.$title_info['rank_up_num']);
            if(!$admire_info){
                $admire_info = $title_info;
                $admire_info['is_receive'] = 1;
            }
        }else{
            $admire_info =  $title_obj->getTitleInfo($where.' AND tag_id ='.TitleModel::ADMIRE);
        }
        //是否满足领取资格．
        $admire_info['is_qualified'] = $user_info['admire_money'] >= $admire_info['rank_up_num'] ? true : false;
        $admire_info['condition_num'] = $user_info['admire_money'];
        //分享的头衔．
        $share_id = array_intersect($share_title_list,$my_titles);
        if(count($share_id)){
            $title_info =  $title_obj->getTitleInfo('title_id ='.implode(',',$share_id));
            $share_info =  $title_obj->getTitleInfo($where.' AND tag_id ='.TitleModel::SHARE.' and rank_up_num >'.$title_info['rank_up_num']);
            if(!$share_info){
                $share_info = $title_info;
                $share_info['is_receive'] = 1;
            }
        }else{
            $share_info =  $title_obj->getTitleInfo($where.' AND tag_id ='.TitleModel::SHARE);
        }

        //是否满足领取资格．
        $share_info['is_qualified'] = $user_info['share_num'] >= $share_info['rank_up_num'] ? true : false;
        $share_info['condition_num'] = $user_info['share_num'];
        $ordinary_title_list = array(
            '0'=>$reply_info,
            '1'=>$admire_info,
            '2'=>$share_info,
        );

        return $ordinary_title_list;
    }


    /**
     *  获取用户当前头衔里是否有该类型的头衔．
     */
    public function getIsOrdinaryTypeTitle($user_id,$tag_id){
        return $this->alias('u')
            ->join('tp_title AS t ON u.title_id = t.title_id')
            ->field('u.title_id,u.user_id,u.user_title_id')
            ->where('u.user_id = ' . $user_id.' AND t.tag_id='.$tag_id)
            ->find();
    }

    /**
     * 获取我的所有头衔列表
     * @author ccy
     * @param string $user_id
     * @return array 头衔列表
     * @todo 获取所有头衔列表
     */
    public function getMyTotalTitleList($user_id)
    {
        return $this->alias('u')
            ->join('tp_title AS t ON u.title_id = t.title_id')
            ->where('u.user_id = ' . $user_id.' AND isuse = 1')
            ->order('u.addtime desc')
            ->limit(1000000)
            ->select();
    }

    public function getListData($user_title_list){

        $title_obj = new TitleModel();
        foreach($user_title_list as $k => $v){
            //头衔名称
            $user_title_list[$k]['title_name'] = $title_obj->getTitleField($v['title_id'],'title_name');
            $user_title_list[$k]['title_color'] = $title_obj->getTitleField($v['title_id'],'color');
        }
        return $user_title_list;
    }


    public function getUserAdornTitle($user_id){
        $title_list = $this->getUserTitleList('user_id ='.$user_id .' and is_adorn = 1','adorn_time asc');
        $title_list = $this->getListData($title_list);
        return $title_list;
    }
}
